﻿using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Xml;

namespace ConfigServices.XML
{
	public static class XMLService
	{
		/// <summary>
		/// 将 XmlDocument 保存至本地 XML 文件
		/// </summary>
		/// <param name="xmlDoc">调用者提供的 XmlDocument 实例</param>
		/// <param name="xmlFilePath">本地 XML 存放路径</param>
		/// <returns></returns>
		public static bool Save(XmlDocument xmlDoc, string xmlFilePath)
		{
			bool saveSuccessful = false;
			StreamWriter streamWriter = null;
			XmlWriter xmlWriter = null;
			try
			{
				streamWriter = new StreamWriter(xmlFilePath, false, Encoding.UTF8);
				XmlWriterSettings writerSettings = new XmlWriterSettings();
				writerSettings.Indent = true;
				xmlWriter = XmlTextWriter.Create(streamWriter, writerSettings);
				xmlDoc.WriteTo(xmlWriter);
				xmlWriter.Close();
				streamWriter.Close();

				saveSuccessful = true;
			}
			catch (Exception error)
			{
				saveSuccessful = false;
				throw error;
			}
			finally
			{
				if (streamWriter != null)
				{
					streamWriter.Close();
				}
				if (xmlWriter !=null)
				{
					xmlWriter.Close();
				}
			}
			return saveSuccessful;
		}

		/// <summary>
		/// 将本地 XML 文件读取到 XmlDocument 实例
		/// </summary>
		/// <param name="xmlFilePath">本地 XML 存放路径</param>
		/// <returns></returns>
		public static XmlDocument Load(string xmlFilePath)
		{
			XmlDocument xmlDoc = new XmlDocument();

			try
			{
				string fileContent = File.ReadAllText(xmlFilePath);
				xmlDoc.LoadXml(fileContent);
			}
			catch (Exception error)
			{
				throw error;
			}

			return xmlDoc;
		}
	}
}
